package mo.tags.stack;

import mo.common.ListNode;

import java.util.Stack;

public class LO2_25 {

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        Stack<Integer> values1 = new Stack<>();
        Stack<Integer> values2 = new Stack<>();
        ListNode tmp = l1;
        while (tmp != null) {
            values1.add(tmp.val);
            tmp = tmp.next;
        }
        tmp = l2;
        while (tmp != null) {
            values2.add(tmp.val);
            tmp = tmp.next;
        }
        ListNode head = null;
        int carry = 0;
        while (!values1.isEmpty() && !values2.isEmpty()) {
            int v1 = values1.pop();
            int v2 = values2.pop();
            ListNode cur = new ListNode((v1 + v2 + carry) % 10);
            carry = (v1 + v2 + carry) / 10;
            cur.next = head;
            head = cur;
        }
        Stack<Integer> left = values1.size() == 0 ? values2 : values1;
        while (!left.isEmpty()) {
            int v = left.pop();
            ListNode cur = new ListNode((v + carry)%10);
            carry = (v + carry) / 10;
            cur.next = head;
            head = cur;
        }
        if (carry != 0) {
            ListNode cur = new ListNode(carry);
            cur.next = head;
            head = cur;
        }
        return head;
    }

}
